﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;
using System.Xml;
using System.Xml.Serialization;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Net;
using System.Net.Sockets;

namespace tools_library
{
    public class NameValuePair
    {
        public string Key;
        public object Value;
        public NameValuePair()
        { }

        public NameValuePair(string key, object value)
        {
            this.Key = key;
            this.Value = value;
        }
    }

    [Serializable()]
    public class SerializableHashtable : List<NameValuePair>
    {
        public void WriteToFile(string filename)
        {
            //open the stream to write
            StreamWriter sw=new StreamWriter(filename);
            XmlSerializer serializer = new XmlSerializer(typeof(SerializableHashtable));
            serializer.Serialize(sw, this);
            sw.Close();
        }

        public void ReadFromFile(string filename)
        {
            if (!File.Exists(filename))
            {
                return;
            }
            //open the stream to read
            StreamReader sr = new StreamReader(filename);
            XmlSerializer serializer = new XmlSerializer(typeof(SerializableHashtable));
            SerializableHashtable ht = serializer.Deserialize(sr) as SerializableHashtable;
            base.Clear();
            foreach (NameValuePair nvp in ht)
            {
                base.Add(nvp);
            }
        }

        public void Add(string key, object value)
        {
            base.Add(new NameValuePair(key, value));
        }

        public bool ContainsKey(string key)
        {
            try
            {
                NameValuePair pair = this.Find(
                    delegate(NameValuePair nvp)
                    {
                        return nvp.Key == key;
                    });
                if (pair == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch 
            { 
                return false; 
            }
        }

        public object this[string key]
        {
            get 
            {
                object val = null;
                NameValuePair pair = this.Find(
                    delegate(NameValuePair nvp)
                    {
                        return nvp.Key == key;
                    });
                if (pair != null)
                    val = pair.Value;
                return val;
            }

            set 
            {
                NameValuePair pair = this.Find(
                    delegate(NameValuePair nvp)
                    {
                        return nvp.Key == key;
                    });
                if (pair != null)
                    pair.Value = value;
            }
        }
    }

    public class HelperTool
    {
        private XmlSerializer Serializer;
        public SerializableHashtable ht;
        private string ConfigFileName;
        private string LogFileName;

        public HelperTool()
        {
            ht = new SerializableHashtable();
            this.ConfigFileName = AppDomain.CurrentDomain.BaseDirectory + "appConfig.dat";
            this.LogFileName = AppDomain.CurrentDomain.BaseDirectory + "logFile.txt";
            ReadHashTable();
        }

        public byte[] BitmapToByte(Bitmap bitmap)
        {
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Png);
            return ms.ToArray();
            //Rectangle rect = new Rectangle(0, 0, data.Width, data.Height);
            //BitmapData bmdata = data.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            //byte[] pixels=null;
            //Marshal.Copy(bmdata.Scan0, pixels, 0, bmdata.Stride * data.Height);
            //return Encoding.ASCII.GetString(pixels);
        }

        public Bitmap ByteToBitmap(byte[] bytes)
        {
            MemoryStream ms = new MemoryStream(bytes);
            Image newImage = Bitmap.FromStream(ms);
            return (Bitmap)newImage;
        }

        public void WriteLog(string strLog)
        {
            try
            {
                StreamWriter sw = new StreamWriter(this.LogFileName, true);
                sw.WriteLine(DateTime.Now.ToString("dd-MMM-yyyy HH:mm:ss") + ": " + strLog);
                sw.Close();
            }
            catch { }
        }

        public void ShowConfigDialog()
        {
            frmConfig config = new frmConfig(ht);
            config.ShowDialog();
            SaveHashTable();
        }

        private void SaveHashTable()
        {
            //serializer = new XmlSerializer(typeof(Hashtable));
            Serializer = new XmlSerializer(typeof(SerializableHashtable));
            StreamWriter sw = null;
            try
            {
                if (ht != null)
                {
                    sw = new StreamWriter(this.ConfigFileName);
                    Serializer.Serialize(sw, ht);
                    sw.Close();
                }
            }
            catch { }
        }

        private void ReadHashTable()
        {
            StreamReader sr=null;
            try
            {
                Serializer = new XmlSerializer(typeof(SerializableHashtable));
                if (File.Exists(this.ConfigFileName))
                {
                    sr = new StreamReader(this.ConfigFileName);
                    //ht = (Hashtable)serializer.Deserialize(sr);
                    ht = (SerializableHashtable)Serializer.Deserialize(sr);
                    sr.Close();
                }
            }
            catch
            { 
            }
        }

        /// <summary>
        /// <remarks>Gets specified setting from the local configuration file</remarks>
        /// </summary>
        public object GetSetting(string key)
        {
            try
            {
                if (ht.ContainsKey(key))
                {
                    return ht[key];
                }
                else
                {
                    return null; //could'nt find the key in the file
                }
            }
            catch 
            {
                return null;
            }
        }

        /// <summary>
        /// <remarks>Saves specified setting to the local configuration file</remarks>
        /// </summary>
        public void SaveSetting(string key, string value)
        {
            try
            {
                if (ht.ContainsKey(key))
                {
                    ht[key] = value;
                }
                else
                {
                    ht.Add(new NameValuePair(key,value));
                }
                SaveHashTable();
            }
            catch { }
        }

        public IPAddress GetAddressFromHost(string hostName)
        {
            //IPAddress address = Dns.GetHostEntry(txtRemoteHost.Text).AddressList[0];
            IPHostEntry host = Dns.GetHostEntry(hostName);
            IPAddress[] addresses = Dns.GetHostAddresses(host.HostName);
            IPAddress address;
            if (addresses[0].ToString() == "127.0.0.1" && addresses.Length > 1)
            {
                address = addresses[1];
            }
            else
            {
                address = addresses[0];
            }
            return address;
        }
    }
}
